<template>
  <view class="analysis-container">
    <!-- 电子宠物区域 -->
    <view class="pet-container">
      <view class="pet-header">
        <text class="pet-title">我的健康宠物</text>
        <view class="pet-stats">
          <view class="pet-exp">
            <view class="stat-header">
              <text>经验值: {{ petExp }}/{{ nextLevelExp }}</text>
              <u-image width="32rpx" height="32rpx" :src="statIcons.exp" mode="aspectFit"></u-image>
            </view>
            <u-line-progress :percentage="(petExp / nextLevelExp) * 100" height="14" activeColor="#58cc02" />
          </view>
          <view class="pet-intimacy">
            <view class="stat-header">
              <text>亲密度: {{ petIntimacy }}/100</text>
              <u-image width="32rpx" height="32rpx" :src="statIcons.intimacy" mode="aspectFit"></u-image>
            </view>
            <u-line-progress :percentage="petIntimacy" height="14" activeColor="#ce82ff" />
          </view>
        </view>
      </view>
      <view class="pet-body">
        <u-image class="pet-image" :src="petImages[petLevel]" width="240rpx" height="240rpx" mode="aspectFit"></u-image>
        <view class="pet-info">
          <text class="pet-name">{{ petName }}</text>
          <text class="pet-level">等级: {{ petLevel + 1 }}/5</text>
          <text class="pet-desc">{{ petDescriptions[petLevel] }}</text>
        </view>
      </view>
      <view class="pet-tip">
        <u-icon name="info-circle" color="#1cb0f6" size="16"></u-icon>
        <text>记录健康数据可增加经验值，连续记录可提升亲密度！</text>
      </view>
    </view>

    <!-- 拍照记录健康部分 -->
    <view class="photo-section">
      <view class="photo-header">
        <text class="photo-title">《饕餮智析》+AI大模型分析 您的饮食</text>
      </view>
      <view class="photo-content" @click="takePhoto">
        <image class="photo-icon" src="../../static/input/拍照.png" mode="aspectFit"></image>
        <text class="photo-desc">点击拍照记录饮食</text>
      </view>
    </view>

    <!-- 相机组件区域 -->
    <view class="camera-container" v-if="showCamera">
      <view class="close-btn" @click="closeCamera">
        <u-icon name="close" color="#fff" size="26"></u-icon>
      </view>

      <camera v-if="isAuth" class="camera" device-position="back" flash="off" @error="handleCameraError"></camera>

      <!-- 照片预览区域 -->
      <view class="photo-preview" v-if="healthPhotos.length > 0">
        <image v-for="(photo, index) in healthPhotos" :key="index" :src="photo" class="preview-img"
          @click="previewPhoto(index)"></image>
        <text class="photo-count">{{ healthPhotos.length }}/3</text>
      </view>

      <!-- 拍照按钮区域 -->
      <view class="camera-controls">
        <view class="image-btn" @click="takeCameraPhoto">
          <image src="../../static/input/拍照.png" class="take-photo-btn"></image>
        </view>
      </view>
    </view>

    <!-- 今日健康记录部分 -->
    <view class="section-title">
      <text>今日健康记录</text>
      <u-line color="#1cb0f6" length="100%" />
    </view>

    <!-- 底部用户输入部分 -->
    <view class="user-input-section">
      <u-grid col="2" :border="false">
        <!-- 1. 血糖血脂血压 -->
        <u-grid-item>
          <view class="input-card blood-card" @click="navigateToInput('blood')">
            <image class="card-icon" src="../../static/input/血糖血脂血压.png" mode="aspectFit"></image>
            <view class="card-content">
              <text class="card-title">血糖血脂血压</text>
              <text class="card-desc">记录今日三高指标</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="24"></u-icon>
          </view>
        </u-grid-item>

        <!-- 2. 运动情况输入 -->
        <u-grid-item>
          <view class="input-card exercise-card" @click="navigateToInput('exercise')">
            <image class="card-icon" src="../../static/input/锻炼情况.png" mode="aspectFit"></image>
            <view class="card-content">
              <text class="card-title">运动情况</text>
              <text class="card-desc">记录今日运动数据</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="24"></u-icon>
          </view>
        </u-grid-item>

        <!-- 3. 生活习惯输入 -->
        <u-grid-item>
          <view class="input-card habit-card" @click="navigateToInput('habit')">
            <image class="card-icon" src="../../static/input/生活习惯.png" mode="aspectFit"></image>
            <view class="card-content">
              <text class="card-title">生活习惯</text>
              <text class="card-desc">记录作息及日常习惯</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="24"></u-icon>
          </view>
        </u-grid-item>

        <!-- 4. 身体档案 -->
        <u-grid-item>
          <view class="input-card profile-card" @click="navigateToInput('profile')">
            <image class="card-icon" src="../../static/input/身体档案.png" mode="aspectFit"></image>
            <view class="card-content">
              <text class="card-title">身体档案</text>
              <text class="card-desc">更新身体基础数据</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="24"></u-icon>
          </view>
        </u-grid-item>

        <!-- 5. 心理情况 -->
        <u-grid-item>
          <view class="input-card mental-card" @click="navigateToInput('mental')">
            <image class="card-icon" src="../../static/input/心理.png" mode="aspectFit"></image>
            <view class="card-content">
              <text class="card-title">心理情况</text>
              <text class="card-desc">记录今日心理状态</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="24"></u-icon>
          </view>
        </u-grid-item>

        <!-- 6. 地理位置 -->
        <u-grid-item>
          <view class="input-card location-card" @click="navigateToInput('location')">
            <image class="card-icon" src="../../static/input/地理位置.png" mode="aspectFit"></image>
            <view class="card-content">
              <text class="card-title">地理位置</text>
              <text class="card-desc">记录今日活动区域</text>
            </view>
            <u-icon name="arrow-right" color="#999" size="24"></u-icon>
          </view>
        </u-grid-item>
      </u-grid>
    </view>

    <!-- 底部导航栏由pages.json的tabBar配置自动生成 -->
  </view>
</template>

<script>
export default {
  data() {
    return {
      // 宠物相关数据
      petName: '健康精灵',
      petLevel: 0, // 0-4对应五个阶段
      petExp: 35,
      nextLevelExp: 100,
      petIntimacy: 60,
      petImages: [
        '../../static/pet/第一阶段.png',
        '../../static/pet/第二阶段.png',
        '../../static/pet/第三阶段.png',
        '../../static/pet/第四阶段.png',
        '../../static/pet/第五阶段.png'
      ],
      statIcons: {
        exp: '../../static/pet/经验值.png',
        intimacy: '../../static/pet/亲密度.png'
      },
      petDescriptions: [
        '我刚出生，需要你的健康记录让我成长！',
        '我长大了一点，继续坚持健康生活吧！',
        '我感觉更有活力了，你的健康习惯真棒！',
        '我变得更强壮了，你的努力没有白费！',
        '我已经成熟啦，你已经养成了很好的健康习惯！'
      ],
      showCamera: false,
      isAuth: false,
      healthPhotos: []
    }
  },
  // 页面加载时检查摄像头授权
  onLoad() {
    // 检查摄像头授权状态
    this.checkCameraAuth();
  },
  methods: {
    // 导航方法
    navigateTo(url) {
      // 使用switchTab方法跳转到tabBar页面
      uni.switchTab({
        url: url
      })
    },
    // 跳转到对应的输入页面
    navigateToInput(type) {
      uni.showToast({
        title: `即将进入${type}输入页面`,
        icon: 'none'
      })
      // 实现页面跳转功能
      uni.navigateTo({
        url: `/pages/input/${type}`
      })

      // 记录数据后增加经验和亲密度
      this.addPetExp(10);
      this.addPetIntimacy(5);
    },
    // 增加宠物经验值
    addPetExp(value) {
      this.petExp += value;
      // 检查是否可以升级
      if (this.petExp >= this.nextLevelExp && this.petLevel < 4) {
        this.petExp = this.petExp - this.nextLevelExp;
        this.petLevel++;
        this.nextLevelExp = this.nextLevelExp + 50; // 每级所需经验值增加
        uni.showToast({
          title: '恭喜！健康宠物升级啦！',
          icon: 'success'
        });
      }
    },
    // 增加宠物亲密度
    addPetIntimacy(value) {
      this.petIntimacy += value;
      if (this.petIntimacy > 100) {
        this.petIntimacy = 100;
      }
    },
    // 检查摄像头授权
    checkCameraAuth() {
      const _this = this;
      uni.getSetting({
        success: res => {
          if (res.authSetting['scope.camera']) {
            // 用户已经授权
            _this.isAuth = true;
          } else {
            // 用户还没有授权，向用户发起授权请求
            uni.authorize({
              scope: 'scope.camera',
              success() {
                // 用户同意授权
                _this.isAuth = true;
              },
              fail() {
                // 用户不同意授权
                _this.openSetting('camera');
              }
            });
          }
        },
        fail: res => {
          console.log('获取用户授权信息失败');
        }
      });
    },
    // 打开设置页面
    openSetting(scope) {
      return new Promise((resolve, reject) => {
        uni.showModal({
          title: '提示',
          content: scope === 'camera' ? '需要您授权使用摄像头' : '需要您授权使用麦克风',
          confirmText: '去设置',
          cancelText: '取消',
          success: res => {
            if (res.confirm) {
              uni.openSetting({
                success: res => {
                  if (scope === 'camera' && res.authSetting['scope.camera']) {
                    resolve(true);
                  } else if (scope === 'record' && res.authSetting['scope.record']) {
                    resolve(true);
                  } else {
                    reject(false);
                  }
                }
              });
            } else {
              reject(false);
            }
          }
        });
      });
    },
    // 打开相机
    takePhoto() {
      if (!this.isAuth) {
        this.checkCameraAuth();
        return;
      }
      this.showCamera = true;
    },
    // 关闭相机
    closeCamera() {
      this.showCamera = false;
    },
    // 实际拍照
    takeCameraPhoto() {
      if (this.healthPhotos.length >= 3) {
        // 最多拍3张照片
        uni.showToast({
          title: '最多只能添加3张照片',
          icon: 'none'
        });
        return;
      }

      const ctx = uni.createCameraContext();
      ctx.takePhoto({
        quality: 'normal', // 成像质量
        success: res => {
          uni.showLoading({
            title: '图片处理中'
          });

          // 添加照片到数组
          this.healthPhotos.push(res.tempImagePath);

          // 增加宠物经验和亲密度
          this.addPetExp(5);
          this.addPetIntimacy(3);

          uni.hideLoading();

          uni.showToast({
            title: '拍照成功',
            icon: 'success'
          });

          // 如果已经拍了3张照片，自动关闭相机
          if (this.healthPhotos.length >= 3) {
            this.closeCamera();
          }
        },
        fail: err => {
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          });
        }
      });
    },
    // 预览照片
    previewPhoto(index) {
      uni.previewImage({
        urls: this.healthPhotos,
        current: this.healthPhotos[index]
      });
    },
    // 处理相机错误
    handleCameraError(e) {
      console.error('相机错误', e);
      uni.showToast({
        title: `相机错误，请检查权限设置`,
        icon: 'none'
      });
      this.isAuth = false;
    }
  }
}
</script>

<style lang="scss">
/* 多邻国风格的颜色变量 */
$duolingo-green: #58cc02;
$duolingo-blue: #1cb0f6;
$duolingo-purple: #ce82ff;
$duolingo-orange: #ff9600;
$duolingo-red: #ff4b4b;
$duolingo-light-gray: #f7f7f7;
$duolingo-dark-gray: #4b4b4b;

.analysis-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: $duolingo-light-gray;
  position: relative;
  padding-bottom: 120rpx;
  /* 为底部导航栏留出空间 */
}

/* 中间AI对话框部分 */
.ai-chat-box {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.ai-message {
  font-size: 28rpx;
  color: $duolingo-dark-gray;
  padding: 20rpx 0;
}

.input-box {
  margin-top: 10rpx;
}

/* 区域标题 */
.section-title {
  padding: 20rpx 30rpx 10rpx;
  font-size: 32rpx;
  font-weight: bold;
  color: $duolingo-dark-gray;
}

/* 底部用户输入部分 */
.user-input-section {
  padding: 10rpx 20rpx;
}

/* 输入卡片样式 */
.input-card {
  margin: 10rpx;
  padding: 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.input-card:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.card-icon {
  width: 80rpx;
  height: 80rpx;
  margin-right: 20rpx;
}

.card-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: $duolingo-dark-gray;
  margin-bottom: 4rpx;
}

.card-desc {
  font-size: 22rpx;
  color: #999;
}

/* 不同卡片的样式 */
.blood-card {
  border-left: 6rpx solid $duolingo-red;
}

.exercise-card {
  border-left: 6rpx solid $duolingo-green;
}

.habit-card {
  border-left: 6rpx solid $duolingo-blue;
}

.profile-card {
  border-left: 6rpx solid $duolingo-orange;
}

.mental-card {
  border-left: 6rpx solid $duolingo-purple;
}

.location-card {
  border-left: 6rpx solid #2196F3;
}

/* 电子宠物区域样式 */
.pet-container {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.pet-header {
  display: flex;
  flex-direction: column;
  margin-bottom: 30rpx;
}

.pet-title {
  font-size: 36rpx;
  font-weight: bold;
  color: $duolingo-dark-gray;
  margin-bottom: 20rpx;
}

.pet-stats {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.pet-exp,
.pet-intimacy {
  display: flex;
  flex-direction: column;

  .stat-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8rpx;

    text {
      font-size: 26rpx;
      color: $duolingo-dark-gray;
    }
  }
}

.pet-body {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  margin: 20rpx 0;
  border-top: 2rpx dashed #eee;
  border-bottom: 2rpx dashed #eee;
}

.pet-image {
  margin-right: 40rpx;
}

.pet-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.pet-name {
  font-size: 34rpx;
  font-weight: bold;
  color: $duolingo-dark-gray;
  margin-bottom: 10rpx;
}

.pet-level {
  font-size: 30rpx;
  color: $duolingo-orange;
  margin-bottom: 16rpx;
}

.pet-desc {
  font-size: 28rpx;
  color: #666;
  line-height: 1.4;
}

.pet-tip {
  display: flex;
  align-items: center;
  margin-top: 20rpx;
  padding: 16rpx;
  background-color: rgba($duolingo-blue, 0.1);
  border-radius: 12rpx;

  text {
    margin-left: 10rpx;
    font-size: 26rpx;
    color: #666;
  }
}

/* 拍照记录健康部分 */
.photo-section {
  background-color: #fff;
  border-radius: 20rpx;
  margin: 20rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  margin-top: 20rpx;
  margin-bottom: 20rpx;
}

.photo-header {
  font-size: 36rpx;
  font-weight: bold;
  color: $duolingo-dark-gray;
  margin-bottom: 20rpx;
}

.photo-content {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: rgba($duolingo-blue, 0.1);
  border-radius: 12rpx;
  transition: all 0.3s;

  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

.photo-icon {
  width: 80rpx;
  height: 80rpx;
  margin-right: 20rpx;
}

.photo-desc {
  font-size: 28rpx;
  color: $duolingo-dark-gray;
}

/* 相机组件区域 */
.camera-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  z-index: 999;
  display: flex;
  flex-direction: column;
}

.camera {
  width: 100%;
  height: 80vh;
}

.camera-controls {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20vh;
  background-color: #222;
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 20rpx 0;
}

.close-btn {
  position: absolute;
  top: 40rpx;
  left: 40rpx;
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.image-btn {
  width: 140rpx;
  height: 140rpx;
  border-radius: 50%;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.5);
}

.take-photo-btn {
  width: 80rpx;
  height: 80rpx;
}

.photo-preview {
  position: absolute;
  right: 40rpx;
  bottom: 40rpx;
  display: flex;
  flex-direction: row;
  z-index: 1000;
}

.preview-img {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-left: 20rpx;
  border: 4rpx solid #fff;
}

.photo-count {
  position: absolute;
  bottom: -30rpx;
  right: 0;
  font-size: 24rpx;
  color: #fff;
}
</style>